package Pet.Management.service.impl;

import Pet.Management.domain.entity.Payment;
import Pet.Management.repository.PaymentRepository;
import Pet.Management.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private PaymentRepository paymentRepository;

    @Override
    @Transactional
    public Payment createPayment(Payment payment) {
        payment.setStatus((byte) 0); // 设置为待支付状态
        payment.setCreateTime(new Date());
        return paymentRepository.save(payment);
    }

    @Override
    @Transactional
    public Payment updatePaymentStatus(Long paymentId, String status) {
        Payment payment = paymentRepository.findById(paymentId)
                .orElseThrow(() -> new RuntimeException("Payment not found"));
        payment.setStatus(Byte.parseByte(status));
        payment.setUpdateTime(new Date());
        
        if ("1".equals(status)) { // 支付成功
            payment.setPayTime(new Date());
        }
        
        return paymentRepository.save(payment);
    }

    @Override
    public Payment getPayment(Long paymentId) {
        return paymentRepository.findById(paymentId)
                .orElseThrow(() -> new RuntimeException("Payment not found"));
    }

    @Override
    public Payment getPaymentDetails(Long paymentId) {
        return getPayment(paymentId); // 直接返回支付记录，因为已经包含了所有详情
    }

    @Override
    public Page<Payment> getUserPayments(Long userId, Pageable pageable) {
        return paymentRepository.findByUserId(userId, pageable);
    }

    @Override
    public Payment getOrderPayment(Long orderId) {
        return paymentRepository.findByOrderId(orderId);
    }

    @Override
    public boolean validatePaymentAmount(Long orderId, Double amount) {
        Payment payment = paymentRepository.findByOrderId(orderId);
        if (payment == null) {
            return false;
        }
        // 比较金额是否匹配，考虑到浮点数精度问题，使用差值小于0.01来判断
        return Math.abs(payment.getAmount() - amount) < 0.01;
    }

    @Override
    @Transactional
    public Payment handlePaymentCallback(String outTradeNo, String transactionId, String status) {
        Payment payment = paymentRepository.findByOutTradeNo(outTradeNo);
        if (payment == null) {
            throw new RuntimeException("Payment not found with outTradeNo: " + outTradeNo);
        }
        
        payment.setTransactionId(transactionId);
        payment.setStatus(Byte.parseByte(status));
        payment.setUpdateTime(new Date());
        
        if ("1".equals(status)) { // 支付成功
            payment.setPayTime(new Date());
        }
        
        return paymentRepository.save(payment);
    }

    @Override
    @Transactional
    public Payment refund(Long paymentId, Double amount, String reason) {
        Payment payment = paymentRepository.findById(paymentId)
                .orElseThrow(() -> new RuntimeException("Payment not found"));
        
        // 检查支付状态是否为已支付
        if (payment.getStatus() != 1) {
            throw new RuntimeException("Payment status is not valid for refund");
        }
        
        // 检查退款金额是否合法
        if (amount > payment.getAmount()) {
            throw new RuntimeException("Refund amount cannot be greater than payment amount");
        }
        
        payment.setStatus((byte) 3); // 设置为退款状态
        payment.setUpdateTime(new Date());
        
        return paymentRepository.save(payment);
    }

    @Override
    @Transactional
    public Payment cancelPayment(Long paymentId) {
        Payment payment = paymentRepository.findById(paymentId)
                .orElseThrow(() -> new RuntimeException("Payment not found"));
        
        // 只有待支付状态的订单才能取消
        if (payment.getStatus() != 0) {
            throw new RuntimeException("Payment cannot be cancelled in current status");
        }
        
        payment.setStatus((byte) 4); // 设置为已取消状态
        payment.setUpdateTime(new Date());
        
        return paymentRepository.save(payment);
    }
} 